import React from 'react';
import './index.scss';
import { CaretRightOutlined, DeleteOutlined, FormOutlined, PlusOutlined } from '@ant-design/icons';
import { GetGroupTreeList } from '@/common';
import { SvgIcon } from '@/components/icon';

export type TreeClickType = 'update' | 'edit' | 'delete' | 'default' | 'open';

type HandleClick = (
  e: React.MouseEvent<HTMLSpanElement, MouseEvent>,
  value: GetGroupTreeList,
  type: TreeClickType,
) => void;

interface TreeNodeProps {
  item: GetGroupTreeList;
  activeKey?: string;
  level?: number;
  open?: string[];
  resizeWidth: number;
  onClick: HandleClick;
  expandedStatus: boolean;
  findParentName: (id: string) => string | null;
}

const findNode = (tree: GetGroupTreeList[], id?: string): GetGroupTreeList | null => {
  if (id === undefined) return null;

  for (const node of tree) {
    if (node.id === id) {
      return node; // 找到目标节点
    }
    if (node.children && node.children.length > 0) {
      const result = findNode(node.children, id); // 递归查找子节点
      if (result) {
        return result;
      }
    }
  }
  return null; // 未找到
};

const TreeNode = ({
  item,
  level = 0,
  open,
  onClick,
  activeKey,
  expandedStatus,
  findParentName,
  resizeWidth,
}: TreeNodeProps) => {
  const openNode = open && open?.findIndex((value) => value === item.id) > -1;
  const childrenStatus = findNode(item.children, activeKey);
  const parentName = findParentName && findParentName(item.id);
  const iconName = () => {
    if (item.level === 0) {
      return 'ai-classa';
    }
    if (item.level === 1) {
      return 'ai-classb';
    }

    return 'ai-calssc';
  };

  return (
    <>
      <div
        className={`select group relative flex cursor-pointer select-none items-center justify-between py-[14px] pl-2 pr-[10px]  text-[#1D1D1D] ${
          item.id === activeKey ? 'select-active' : ''
        } ${level < 2 ? 'text-sm' : 'text-[12px]'}`}
        onClick={(e) => onClick(e, item, 'default')}
      >
        <div
          className="flex flex-1 items-center"
          style={{
            paddingLeft: `${24 * level}px`,
          }}
        >
          {!expandedStatus && (
            <div className="h-5 w-5">
              {item.children && item.children.length > 0 && !expandedStatus && (
                <CaretRightOutlined
                  rotate={openNode || childrenStatus ? 90 : 0}
                  onClick={(e) => onClick(e, item, 'open')}
                />
              )}
            </div>
          )}

          <div className="flex flex-1 items-center pl-1 font-medium">
            {!expandedStatus ? (
              <div
                className={`truncate`}
                style={{
                  width: '100%',
                  // width: expandedStatus
                  //   ? 'auto'
                  //   : 128 - (level - 1) * 24 - (item.level <= 1 ? 24 : 0),
                }}
              >
                <div className="flex items-center gap-2">
                  {/* <div className="rounded-md bg-blue px-1 text-white"> */}
                  <SvgIcon icon={iconName()} />
                  {/* {item.level === 0 && '校'}
                    {item.level === 1 && '院'}
                    {item.level === 2 && '班'} */}
                  {/* </div> */}

                  <div
                    className={`truncate`}
                    style={{
                      // width: expandedStatus
                      //   ? 'auto'
                      //   : 92 - (level - 1) * 24 - (item.level <= 1 ? 24 : 0),
                      // width: resizeWidth - (level - 1) * 24 - 20 - 4 - 22 - 54,
                      width: resizeWidth - 148 - (level - 1) * 24 - (item.level <= 1 ? 24 : 0),
                    }}
                  >
                    {item.name}
                  </div>
                </div>
              </div>
            ) : (
              <div
                className="flex flex-1 truncate"
                style={{
                  maxWidth: resizeWidth - 18,
                }}
              >
                {parentName && (
                  <div
                    className="truncate"
                    style={{
                      maxWidth: resizeWidth / 2 - 18,
                      // maxWidth: 108,
                      flex: '0 1 auto',
                    }}
                  >
                    {parentName}
                  </div>
                )}
                {parentName && <div>/</div>}
                <div
                  className="truncate"
                  style={{
                    // maxWidth: parentName ? resizeWidth / 2 - 8 : resizeWidth - 18,
                    flex: '1 1 0',
                    // maxWidth: parentName ? 108 : 222,
                  }}
                >
                  {item.name}
                </div>
              </div>
            )}
          </div>
        </div>

        <div className="absolute right-[10px]">
          <div
            className={`items-center ${
              item.id === activeKey && item.system_code !== 'default' && !expandedStatus
                ? 'flex'
                : `hidden ${
                    item.system_code !== 'default' && !expandedStatus && 'group-hover:flex'
                  }`
            }`}
          >
            {/* {item.level === 0 ? (
              <div className="flex items-center" onClick={(e) => onClick(e, item, 'update')}>
                <PlusOutlined />
                <div className="pl-1 text-xs">添加组织</div>
              </div>
            ) : (
              <>
                {item.level < 2 && <PlusOutlined onClick={(e) => onClick(e, item, 'update')} />}
                <FormOutlined className="mx-3" onClick={(e) => onClick(e, item, 'edit')} />
                <DeleteOutlined onClick={(e) => onClick(e, item, 'delete')} />
              </>
            )} */}
            {item.level < 2 && <PlusOutlined onClick={(e) => onClick(e, item, 'update')} />}
            <FormOutlined className="mx-3" onClick={(e) => onClick(e, item, 'edit')} />
            {item.level > 0 && <DeleteOutlined onClick={(e) => onClick(e, item, 'delete')} />}
          </div>
        </div>
      </div>
      {((openNode && item.children && item.children.length > 0) || childrenStatus) &&
        !expandedStatus && (
          <>
            {item.children.map((child) => (
              <TreeNode
                item={child}
                level={level + 1}
                key={child.id}
                open={open}
                onClick={onClick}
                activeKey={activeKey}
                expandedStatus={expandedStatus}
                findParentName={findParentName}
                resizeWidth={resizeWidth}
              />
            ))}
          </>
        )}
    </>
  );
};

export interface TreeProps {
  treeData: GetGroupTreeList[]; // 树形数据
  activeKey?: string; // 选中的key值
  expandedKeys?: string[]; // 打开的列表值
  onClick: (value: GetGroupTreeList, type: TreeClickType) => void; // 点击事件
  expandedStatus?: boolean;
  findParentName: (id: string) => string | null;
  resizeWidth: number;
}

const Tree = ({
  treeData,
  activeKey,
  expandedKeys,
  onClick,
  expandedStatus = false,
  findParentName,
  resizeWidth,
}: TreeProps) => {
  const handleClick: HandleClick = (e, value, type) => {
    e.stopPropagation();
    onClick(value, type);
  };

  return (
    <>
      {treeData.map((item) => (
        <TreeNode
          item={item}
          key={item.id}
          open={expandedKeys}
          onClick={handleClick}
          activeKey={activeKey}
          expandedStatus={expandedStatus}
          findParentName={findParentName}
          resizeWidth={resizeWidth}
        />
      ))}
    </>
  );
};

export default Tree;
